<?php
class taskController extends base
{
    public function __construct()
    {
        parent::__construct('default');
    }
    /**
     * 删除重复收藏信息
    */
    public function dodelRepeatColl()
    {
        set_time_limit(0);
        $time = time();
        $source = $this->db->getAll("select collection_id, uid, news_id from r_news_collection order by collection_id DESC");
        $data = array();
        if(!empty($source))
        {
            foreach ($source as $v) {
                extract($v);
                $key = $uid.'_'.$news_id;
                if(isset($data[$key]) && $data[$key] == 1){
                    $this->db->query("DELETE FROM r_news_collection WHERE uid='{$uid}' and news_id= '{$news_id}' and collection_id !='{$collection_id}'");
                    $data[$key] = 0;
                }
                else if(!isset($data[$key]))
                {
                    $data[$key] = 1;
                }
                unset($key, $uid, $news_id, $collection_id);
            }
        }
        var_dump($time - time());
        exit;
    }
    /**
     * 修正帖子热门列表排序
    */
    public function docorBoardHotOrder()
    {
        $nids = $this->db->getCol('select news_id from r_news where is_show = 1');
        foreach ($nids as $postId) {
            $postInfo = $this->load('bbs')->getPostInfo($postId);
            $lastCT = $this->db->getOne("select add_time from r_news_comment where news_id = '{$postId}' and is_show = 1 order by comment_id DESC limit 1");
            $lastCT = intval($lastCT);
            foreach ($postInfo['board'] as $v) {
                if(!empty($v['boardId']) && $this->redis->ZSCORE(REDIS_PREFIX.'BoardPostList'.$v['boardId'].'_New', $postId) != false)
                {
                    $this->redis->zadd(REDIS_PREFIX.'BoardPostList'.$v['boardId'].'_Hot', $lastCT, $postId);
                }
            }
        }
        exit(date("Y-m-d H:i:s"));
    }
    /**
     * 修正用户总排行榜
    */
    public function docorUserRank()
    {
        $time = strtotime("2015-01-22"); // 1421856000
        // $time = 0;
        $uids = $this->db->getCol("select distinct(uid) from r_data where addtime >= '{$time}' order by addtime ASC");
        foreach ($uids as $key => $uid) {
            $total = $this->db->getOne("select sum(mileage) from r_data where uid = '{$uid}' and is_delete = 0");
            $total = round($total , 2);
            if($this->db->update("update r_user set total_mileage = '{$total}' where uid = '{$uid}'") != false)
            {
                if($this->redis->EXISTS(REDIS_PREFIX.'UserInfo_'.$uid))
                {
                    $this->redis->hset(REDIS_PREFIX.'UserInfo_'.$uid, "total_mileage", $total);
                }
                $this->redis->zadd(REDIS_PREFIX.'StandingsMileage', $total, $uid);
            }
            else
            {
                var_dump("db false");
            }
            unset($uid, $total);
        }
        exit;
    }
    /**
     * 修正用户跑步数据
    */
    public function docorUserRunData()
    {
        $p = common::request('p', 'G', 1);
        $offset = 5000;
        $start = ($p -1) * $offset;
        $uids = $this->db->getCol("select distinct(uid) from r_data order by addtime ASC limit $start, $offset");
        if(!empty($uids))
        {
            foreach ($uids as $key => $uid) {
                $total = $this->db->getRow("select sum(mileage) as total_mileage, count(*) as total_rate from r_data where uid = '{$uid}' and is_delete = 0");
                $total_mileage = round($total['total_mileage'] , 2);
                $total_rate = intval($total['total_rate']);
                $level =common::getLevel($total_mileage);
                if($this->db->update("update r_user set total_mileage = '{$total_mileage}', total_rate = '{$total_rate}',level='{$level}' where uid = '{$uid}'") != false)
                {
                    if($this->redis->EXISTS(REDIS_PREFIX.'UserInfo_'.$uid))
                    {
                        $this->redis->hset(REDIS_PREFIX.'UserInfo_'.$uid, "total_mileage", $total_mileage);
                        $this->redis->hset(REDIS_PREFIX.'UserInfo_'.$uid, "total_rate", $total_rate);
                        $this->redis->hset(REDIS_PREFIX.'UserInfo_'.$uid, "level", $level);
                    }
                    $this->redis->zadd(REDIS_PREFIX.'StandingsMileage', $total_mileage, $uid);
                }
                else
                {
                    var_dump("db false");
                }
                unset($uid, $total,$total_mileage,$total_rate,$level);
            }
        }
        else
        {
            var_dump('empty');
            exit;
        }
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 修正用户跑步数据
    */
    public function docorUserRunLevel()
    {
        $uids = $this->db->getCol("select distinct(uid) from r_data where addtime >='1422374400'");
        if(!empty($uids))
        {
            foreach ($uids as $key => $uid) {
                $this->load('client')->getUserLevelInfo($uid, true);
            }
        }
        else
        {
            var_dump('empty');
            exit;
        }
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 生成群组相关redis
    */
    public function dogroupRedis()
    {
        $this->redis->del(REDIS_PREFIX.'GroupHost');
        $data = $this->db->getAll("select gid, uid, isDismiss from r_group");
        foreach ($data as $v)
        {
            $this->redis->hset(REDIS_PREFIX.'GroupHost', $v['gid'], $v['uid']);
            if(!$v['isDismiss'])
            {
                $members = $this->db->getAll("select gid, uid, role, addtime from r_gmember where role >=0 && role < 3");
                $this->redis->del(REDIS_PREFIX.'GroupRole_'.$v['gid']);
                foreach ($members as $v)
                {
                    $this->redis->hset(REDIS_PREFIX.'GroupRole_'.$v['gid'], $v['uid'], $v['role']);
                    $this->redis->zadd(REDIS_PREFIX.'MGList_'.$v['uid'], $v['addtime'], $v['gid']);
                }
            }
        }
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    public function dodelRepeatNickname()
    {
        $repeatName = $this->db->getAll('select nickname, count(*) as t from r_user group by nickname order by t DESC limit 100');
        foreach ($repeatName as $v) {
            if($v['t'] > 1)
            {
                $nickname = $v['nickname'];
                $users = $this->db->getCol("select uid from r_user where nickname = '{$nickname}' order by uid ASC");
                if($users)
                {
                    foreach ($users as $key => $uid) {
                        if($key == 0)
                        {
                            continue;
                        }
                        $newName = $this->load('user')->makeNickname($nickname);
                        if($this->db->update("update r_user set nickname = '{$newName}' where uid = '{$uid}'"))
                        {
                            if($this->redis->EXISTS(REDIS_PREFIX.'UserInfo_'.$uid))
                            {
                                $this->redis->hset(REDIS_PREFIX.'UserInfo_'.$uid, 'nickname', $nickname);
                            }
                        }
                    }
                }
            }
            else
            {
                break;
            }
        }
        var_dump('处理完毕');
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    public function docreateGroupBestRecord()
    {
        $groups = $this->db->getCol("select gid from r_group order by gid ASC");
        $recordArr = array('farthest' => '最远跑步纪录',
                           'longest' => '最久跑步纪录',
                           'bestFive' => '5公里最佳纪录',
                           'bestTen' => '10公里最佳纪录',
                           'bestHalf' => '半马最佳纪录',
                           'bestMara' => '全马最佳纪录',
                           'maxTimes' => '跑步次数纪录'
                        );
        foreach ($groups as $gid) {
            foreach ($recordArr as $key => $value) {
                $this->load('group')->createRecord($gid, $key);
            }
        }
        var_dump('生成群组最佳记录完毕');
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    public function docreateGroupMemberRedis()
    {
        $groups = $this->db->getCol("select gid from r_group order by gid ASC");
        foreach ($groups as $gid) {
            $this->redis->del(REDIS_PREFIX.'GroupAdmin_'.$gid);
            $members = $this->db->getAll("select uid, role, addtime from r_gmember where gid = '{$gid}' and role >= 0 order by addtime ASC");
            if($members)
            {
                foreach ($members as $v) {
                    if($v['addtime'] == 0)
                    {
                        $v['addtime'] = $this->db->getOne("select addtime from r_group_add where gid = '{$gid}' and uid = '".$v['uid']."'");
                        $this->db->update("update r_gmember set addtime = '".$v['addtime']."' where gid = '{$gid}' and uid = '".$v['uid']."'");
                    }
                    switch ($v['role']) {
                        case '0':
                            $score = $v['addtime'];
                            break;
                        case '1':
                            $score = $v['addtime'] * 3;
                            break;
                        case '2':
                            $score = $v['addtime'] * 2;
                            break;
                        default:
                            break;
                    }
                    if(isset($score))
                        $this->redis->ZADD(REDIS_PREFIX.'GMB_'.$gid, intval($score), $v['uid']);
                }
            }
        }
        var_dump('重建群组成员列表redis完毕');
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 测试从识货取得装备URL
     */
    public function docreateGearShopUrl()
    {
        $gears = $this->db->getall("select gearId, name from r_gear where shopUrl = '' order by gearId ASC");
        // $gears = $this->db->getall("select gearId, name from r_gear order by gearId ASC");
        $total = 0;
        $yes = 0;
        $no = 0;
        foreach ($gears as $gear) {
            $total += 1;
            $gear['name'] = stripslashes($gear['name']);
            $shopUrl = 'http://m.shihuo.cn/search/running?search='.urlencode($gear['name']);
            $searchUrl = 'http://m.shihuo.cn/search/runningCheck?search='.urlencode($gear['name']);
            $rel = common::getContents($searchUrl);
            if(common::is_json($rel))
            {
                $rel = json_decode($rel, true);
                if(isset($rel['num']) && $rel['num'] > 0)
                {
                    if($this->db->update("update r_gear set shopUrl = '".$shopUrl."' where gearId = '{$gear['gearId']}'"))
                    {
                        if($this->redis->EXISTS(REDIS_PREFIX.'GearInfo_'.$gear['gearId']))
                        {
                            $this->redis->hset(REDIS_PREFIX.'GearInfo_'.$gear['gearId'], 'shopUrl', $shopUrl);
                        }
                    }
                    $yes += 1;
                }
                else
                {
                    $no += 1;
                }
            }
        }
        var_dump($total, $yes, $no);
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 生成redis 我的群组数据
     */
    public function docreateMyGroupByRole()
    {
        $uids = $this->db->getCol("select distinct(uid) from r_gmember");

        if($uids)
        {
            foreach ($uids as $uid)
            {
                $this->load('group')->createMyGroupByRole($uid);
            }
        }

        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 将redis 拒收推送数据写入数据库
     */
    public function dowriteRefusePushData()
    {
        $start = common::request('start', 'G', 0);
        $limit = common::request('limit', 'G', 1000);

        $start = intval($start);
        $limit = intval($limit);
        $i = 0;
        $success = 0;

        $redisKey = REDIS_PREFIX . 'clientNotReceivePush';
        $cids = $this->redis->SMEMBERS($redisKey);

        if($cids)
        {
            foreach ($cids as $key => $cid)
            {
                if($i >= $limit)
                {
                    break;
                }
                if($key >= $start)
                {
                    if($this->db->updateRowTable('r_client', array('cid' => $cid, 'isAcceptPush' => 0)))
                    {
                        $this->redis->SREM($redisKey, $cid);
                        $success += 1;
                    }
                    $i += 1;
                }
            }
        }
        var_dump($i, $success);
        var_dump(date("Y-m-d H:i:s"));
        exit;
    }
    /**
     * 生成用户收藏REDIS数据
     */
    public function docreateUserCollectList()
    {
        $this->load('bbs')->createUserCollectList();
        echo date('Y-m-d H:i:s')."生成用户收藏REDIS数据\n";
        exit();
    }
    /**
     * 上马活动统计数据
     */
    public function doshMarathonData()
    {
        $topTenGroup = array();
        $topFiveUser = array();

        $db_create_in = " IN ('10431','10435','10477','10595','10601','10602','10630','10640','10641','10659','10663','10664','10666','10674','10682','10695','10707','10711','10721','10722','10735','10737','10743','10744','10771','10782','10783','10786','10789','10790','10794','10795','10799','10803','10807','10813','10817','10818','10822','10823','10829','10839','10840','10844','10853','10855','10868','10869','10870','10871','10885','10886','10892','10905','10911','10913','10930','10936','10940','10950','10965','10966','10970','10980','10986','10994','10999','11000','11004','11014','11021','11025','11039','11040','11047','11052','11076','11090','11135','11149','11151','11153','11223','11273','11303','11305','11320','11365','11386','11411','11415','11421','11444','11484','11487','11494','11497','11499','11500','11502','11503','11518','11521','11523','11527','11533','11536','11539','11540','11542','11544','11547','11549','11550','11561','11563','11565','11568','11569','11573','11574','11576','11580','11581','11589','11615','11619','11620','11622','11625','11639','11648','11649','11666','11669','11672','11677','11678','11679','11681','11685','11692','11701','11705','11710','11711','11712','11714','11722','11727','11730','11732','11734','11735','11737','11741','11744','11748','11753','11756','11758','11759','11760','11768','11769','11772','11774','11777','11783','11788','11790','11791','11805','11809','11810','11812','11813','11814','11820','11824','11828','11829','11831','11836','11838','11844','11847','11849','11850','11852','11890','11891','11892','11894','11896','11897','11900','11909','11915','11921','11928','11934','11939','11941','11944','11945','11946','11947','11948','11949','11952','11954','11957','11958','11959','11960','11962','11966','11970','11971','11972','11973','11977','11989','11992','11994','11995','11999','12001','12002','12007','12010','12013','12014','12029','12036','12039','12040','12041','12052','12060','12061','12065','12067','12076','12077','12081','12083','12084','12088','12090','12092','12094','12097','12098','12107','12115','12118','12119','12120','12121','12122','12125','12127','12128','12135','12137','12144','12153','12159','12161','12168','12177','12180','12197','12201','12206','12214','12216','12219','12220','12224','12226','12228','12233','12236','12237','12238','12240','12241','12244','12250','12260','12261','12270','12273','12275','12281','12286','12346','12351','12355','12358','12361','12363','12368','12373','12377','12380','12397','12401','12409','12413','12415','12420','12428','12432','12433','12437','12440','12448','12453','12455','12464','12479','12484','12490','12492','12494','12495','12498','12506','12507','12510','12515','12518','12524','12553','12561','12565','12569','12572','12580','12589','12595','12598','12603','12604','12606','12636','12669','12684','12688','12692')";

        // $topTenGroup = $this->db->getAll("select gid, sum(mileage) as total from r_group_run where gid  ". $db_create_in ."  and is_delete = 0 and updatetime >= '1431792000' and updatetime < '1432483200' group by gid order by total DESC limit 10");

        // foreach ($topTenGroup as & $group) {
        //     $host = $this->redis->hget(REDIS_PREFIX.'GroupHost', $group['gid']);
        //     $group['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$host,'nickname');
        // }
        // print_r($topTenGroup);

        $topFiveUser = $this->db->getAll("select uid, gid, total as mileage from (select uid, gid, sum(mileage) as total from r_group_run where gid  ". $db_create_in ."  and is_delete = 0 and updatetime >= '1432396800' and updatetime < '1432483200' group by gid, uid ) as a order by total DESC");

        foreach ($topFiveUser as & $user) {
            $user['nickname'] = $this->redis->hget(REDIS_PREFIX.'UserInfo_'.$user['uid'],'nickname');
        }
        print_r($topFiveUser);
        exit;
    }
    /**
     * 生成群组排行榜数据
     */
    public function docreateGroupRank()
    {
        $gids = $this->db->getCol("select gid from r_group where isDismiss = 0 order by gid ASC");

        foreach ($gids as $gid)
        {
            $this->load('group')->createGMRank($gid, '2015-05');
            $this->load('group')->createGMRank($gid, '201522');
            $this->load('group')->createGMRank($gid, '201521');
            $this->load('group')->createGMRank($gid, '201520');
        }
        var_dump('执行完毕');
    }
    /**
     *  补全帖子缩略图
     */
    public function dopostImgs()
    {
        $news_id = common::request('news_id','G','');
        $p = common::request('p','G', 1);
        $offset = common::request('offset', 'G', 1000);

        $start = ($p - 1) * $offset;

        $sql = "select news_id, thumb_img, sourceImg, (LENGTH(`thumb_img`)-LENGTH(REPLACE(`thumb_img`,\"http\", \"\"))) DIV 4 AS thumb_count, (LENGTH(`sourceImg`)-LENGTH(REPLACE(`sourceImg`,\"http\", \"\"))) DIV 4 AS source_count from r_news";
        $sql .= $news_id ? " where news_id = '$news_id'" : " limit $start, $offset";
        $resource = $this->db->getall($sql);
        

        $thumbMore = array();
        $sourceMore = array();
        foreach ($resource as $k => $v)
        {
            if($v['thumb_count'] > $v['source_count'])
            {
                unset($v['thumb_count'], $v['source_count']);
                $thumbMore[] = $v;
            } 
            else if($v['thumb_count'] < $v['source_count'])
            {
                unset($v['thumb_count'], $v['source_count']);
                $sourceMore[] = $v;
            }
        }

        // 处理缩略图较多的帖子
        /*
        foreach ($thumbMore as $v)
        {
            if(common::is_json($v['thumb_img']))
            {
                $news_id = $v['news_id'];

                $thumb_img = json_decode($v['thumb_img'], true);
                $sourceImg = preg_replace('/thumb/', '', $thumb_img);
                $sourceImg = json_encode($sourceImg);
                
                $this->db->update("update r_news set sourceImg = '{$sourceImg}' where news_id = '{$news_id}'");
                $this->redis->del(REDIS_PREFIX.'NewsInfo_'.$news_id);
            }
        }
        */

        // 处理原图较多的帖子
        foreach ($sourceMore as $v)
        {
            if(common::is_json($v['sourceImg']))
            {
                $news_id = $v['news_id'];

                $sourceImg = json_decode($v['sourceImg'], true);
                $thumbImg = json_decode($v['thumb_img'], true);

                $thumb_img = $thumbImg;
                $imgHost = $this->load('qiniu')->getQNHost();
                $this->load('bbs');
                foreach ($sourceImg as $k => & $v)
                {
                    if(!isset($thumbImg[$k]))
                    {
                        if(preg_match('/joggers-test/', $v) == false)
                        {
                            $v = $_ENV['qiniu']->saveNetImg($v);
                        }
                        $imgInfo = common::getContents($v.'?imageInfo');
                        $imgInfo = json_decode($imgInfo, true);
                        $imgInfo[0] = isset($imgInfo['width']) ? $imgInfo['width'] : 0;
                        $imgInfo[1] = isset($imgInfo['height']) ? $imgInfo['height'] : 0;

                        $imgName = str_replace($imgHost, '', $v);

                        $tmpThumb = $_ENV['bbs']->qiNiuCropImg($v, $imgInfo, 'thumb'.$imgName);
                        $thumb_img[] = $tmpThumb;
                    }
                }

                $sourceImg = json_encode($sourceImg);
                $thumb_img = json_encode($thumb_img);

                $this->db->update("update r_news set sourceImg = '{$sourceImg}', thumb_img = '{$thumb_img}' where news_id = '{$news_id}'");
                $this->redis->del(REDIS_PREFIX.'NewsInfo_'.$news_id);
                echo $news_id,',';
            }
        }

        
        exit;
    }
    /**
     *
     */
    public function doclearPostThumb()
    {
        $news = $this->db->getall("select news_id, thumb_img from r_news where thumb_img LIKE \"%imageMogr2%\"");

        foreach ($news as $v)
        {
            $news_id = $v['news_id'];

            $thumb_img = str_ireplace(array('?imageMogr2\/thumbnail\/200x200!', '?imageMogr2/thumbnail/200x200!'), array('',''), $v['thumb_img']);
            $thumb_img = common::mysql_real_escape_string($thumb_img);

            $this->db->update("update r_news set thumb_img = '{$thumb_img}' where news_id = '{$news_id}'");
            $this->redis->del(REDIS_PREFIX.'NewsInfo_'.$news_id);
        }
        exit;
    }

}